package br.cin.ufpe.corba.iiop;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import br.cin.ufpe.corba.SystemException;

public class Reply {

	private ReplyHeader header;
	private ReplyBody body;
	
	public Reply(Request request, SystemException ex, boolean isSystemException) {
		this.header = new ReplyHeader();
		this.header.setRequestId(request.getHeader().getRequestId());
		if (!isSystemException) {
			this.header.setReplyStatus(ReplyStatusType.USER_EXCEPTION);
		} else {
			this.header.setReplyStatus(ReplyStatusType.SYSTEM_EXCEPTION);
		}
		
		this.body = new SystemExceptionReplyBody(ex);
	}
	
	public Reply(Request request, Object result) {
		this.header = new ReplyHeader();
		this.header.setRequestId(request.getHeader().getRequestId());
		this.header.setReplyStatus(ReplyStatusType.NO_EXCEPTION);
		this.body = new ObjectReplyBody(result);
	}
	
	public Reply(ReplyHeader header, ReplyBody body) {
		this.header = header;
		this.body = body;
	}

	public ReplyHeader getHeader() {
		return header;
	}
	
	public void setHeader(ReplyHeader header) {
		this.header = header;
	}
	
	public ReplyBody getBody() {
		return body;
	}
	
	public void setBody(ReplyBody body) {
		this.body = body;
	}

	public static Reply read(InputStream inputStream) throws IOException, ClassNotFoundException {
		ReplyHeader header = ReplyHeader.read(inputStream);
		ReplyBody body;
		
		if (header.getReplyStatus() != ReplyStatusType.SYSTEM_EXCEPTION) {
			body = ObjectReplyBody.read(inputStream);
		} else {
			body = SystemExceptionReplyBody.read(inputStream);
		}
		
		return new Reply(header, body);
	}

	public void write(OutputStream outputStream) throws IOException {
		this.header.write(outputStream);
		this.body.write(outputStream);		
	}	
	
}
